package com.guoheng.hazard.sys.service.impl.entpr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guoheng.hazard.common.base.Result;
import com.guoheng.hazard.common.constant.CommonConstants;
import com.guoheng.hazard.common.enums.ErrorCodeEnum;
import com.guoheng.hazard.common.enums.PartTypeEnum;
import com.guoheng.hazard.common.util.StringUtils;
import com.guoheng.hazard.sys.mapper.entpr.EntprBasicInfoMapper;
import com.guoheng.hazard.sys.mapper.entpr.MajorHazardMaterialMapper;
import com.guoheng.hazard.sys.mapper.entpr.StorageTankMapper;
import com.guoheng.hazard.sys.model.dto.entpr.EntprScopeDTO;
import com.guoheng.hazard.sys.model.dto.entpr.StorageTankInsertDTO;
import com.guoheng.hazard.sys.model.dto.entpr.StorageTankSelectDTO;
import com.guoheng.hazard.sys.model.dto.entpr.StorageTankUpdateDTO;
import com.guoheng.hazard.sys.model.dto.hazard.MajorHazardMaterialInsertDTO;
import com.guoheng.hazard.sys.model.dto.hazard.MajorHazardMaterialSelectDTO;
import com.guoheng.hazard.sys.model.entity.entpr.EntprBasicInfo;
import com.guoheng.hazard.sys.model.entity.entpr.MajorHazardMaterial;
import com.guoheng.hazard.sys.model.entity.entpr.StorageTank;
import com.guoheng.hazard.sys.service.entpr.StorageTankService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 类功能描述:　StorageTankServiceImpl
 *
 * @author fbl
 * @date 2019-11-12 17:56
 */
@Service
public class StorageTankServiceImpl implements StorageTankService {

    @Resource
    StorageTankMapper storageTankMapper;

    @Resource
    EntprBasicInfoMapper entprBasicInfoMapper;

    @Resource
    MajorHazardMaterialMapper majorHazardMaterialMapper;

    @Override
    public Result getEntprTanks(String entprName, String tankNo, Long entprId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<StorageTankSelectDTO> entprTanks = storageTankMapper.getEntprTanks(entprName, tankNo, entprId);
        for (StorageTankSelectDTO entprTank : entprTanks) {
            Long eId = entprTank.getEntprId();
            // 得到企业姓名
            EntprBasicInfo entprBasicInfoById = entprBasicInfoMapper.getEntprBasicInfoById(eId);

            entprTank.setEntprName(entprBasicInfoById.getEntprName());

            // 得到储罐介质
            List<MajorHazardMaterial> majorMaterials = majorHazardMaterialMapper.getMajorMaterial(PartTypeEnum.PART_TYPE_ONE.getCode(), entprTank.getId());
            entprTank.setMajorHazardMaterials(majorMaterials);
        }

        PageInfo<StorageTankSelectDTO> storageTankPageInfo = new PageInfo<>(entprTanks);
        return Result.success(storageTankPageInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateEntprTanks(StorageTankUpdateDTO storageTankUpdateDTO) {
        // 修改储罐信息
        StorageTank storageTank = new StorageTank();
        BeanUtils.copyProperties(storageTankUpdateDTO, storageTank);
        // 判断储罐编号是否被修改
        StorageTank entprTankById = storageTankMapper.getEntprTankById(storageTank.getId());
        // 编号被修改
        if(!entprTankById.getTankNo().equals(storageTank.getTankNo())){
            // 储罐编号不能重复
            List<StorageTank> allEntprTanks = storageTankMapper.getAllEntprTanks(storageTank.getEntprId());
            for (StorageTank allEntprTank : allEntprTanks) {
                // 编号重复
                if(allEntprTank.getTankNo().equals(storageTank.getTankNo())){
                    return Result.failure(ErrorCodeEnum.SYS_ERR_TANK_NO_REPEAT);
                }
            }
        }
        int updateEntprTanks = storageTankMapper.updateEntprTanks(storageTank);


        if (storageTankUpdateDTO.getMajorHazardMaterialInsertDTOS() != null) {
            List<MajorHazardMaterialSelectDTO> majorHazardMaterialSelectDTOS = storageTankUpdateDTO.getMajorHazardMaterialInsertDTOS();
            // 清空储罐中的介质
            majorHazardMaterialMapper.clearMaterial(PartTypeEnum.PART_TYPE_ONE.getCode(),storageTankUpdateDTO.getId());

            for (MajorHazardMaterialSelectDTO majorHazardMaterialSelectDTO : majorHazardMaterialSelectDTOS) {
                // 重新新增储罐中的介质
                MajorHazardMaterial majorHazardMaterial = new MajorHazardMaterial();
                BeanUtils.copyProperties(majorHazardMaterialSelectDTO, majorHazardMaterial);
                majorHazardMaterial.setPartId(storageTankUpdateDTO.getId());
                majorHazardMaterial.setPartType(PartTypeEnum.PART_TYPE_ONE.getCode());
                majorHazardMaterialMapper.insertSelective(majorHazardMaterial);
            }
        }
        if (updateEntprTanks == CommonConstants.DataBaseOperationStatus.IS_FAILURE) {
            throw new RuntimeException("修改数据失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertEntprTanks(StorageTankInsertDTO storageTankInsertDTO) {
        // 新增储罐信息
        StorageTank storageTank = new StorageTank();
        BeanUtils.copyProperties(storageTankInsertDTO, storageTank);
        // 储罐编号不能重复
        List<StorageTank> allEntprTanks = storageTankMapper.getAllEntprTanks(storageTank.getEntprId());
        for (StorageTank allEntprTank : allEntprTanks) {
            // 编号重复
            if(allEntprTank.getTankNo().equals(storageTank.getTankNo())){
                return Result.failure(ErrorCodeEnum.SYS_ERR_TANK_NO_REPEAT);
            }
        }
        int insertEntprTanks = storageTankMapper.insertEntprTanks(storageTank);
        // 查询最近新增的储罐
        Long lastId = storageTankMapper.getLastId();
        // 新增储罐介质信息
        if (storageTankInsertDTO.getMajorHazardMaterialInsertDTOS() != null) {
            // 新增库区介质信息
            List<MajorHazardMaterialInsertDTO> majorHazardMaterialInsertDTOS = storageTankInsertDTO.getMajorHazardMaterialInsertDTOS();
            for (MajorHazardMaterialInsertDTO majorHazardMaterialInsertDTO : majorHazardMaterialInsertDTOS) {
                MajorHazardMaterial majorHazardMaterial = new MajorHazardMaterial();
                BeanUtils.copyProperties(majorHazardMaterialInsertDTO, majorHazardMaterial);
                majorHazardMaterial.setPartId(lastId);
                majorHazardMaterial.setPartType(PartTypeEnum.PART_TYPE_ONE.getCode());
                majorHazardMaterialMapper.insertSelective(majorHazardMaterial);
            }
        }
        if (insertEntprTanks == CommonConstants.DataBaseOperationStatus.IS_FAILURE) {
            throw new RuntimeException("新增失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteEntprTanks(Long id) {
        // 删除储罐
        StorageTank storageTank = new StorageTank();
        storageTank.setId(id);
        storageTank.setDelFlag(true);
        int deleteEntprTanks = storageTankMapper.updateEntprTanks(storageTank);

        // 删除储罐下的介质
        majorHazardMaterialMapper.deleteMaterial(PartTypeEnum.PART_TYPE_ONE.getCode(), id);
        if (deleteEntprTanks == CommonConstants.DataBaseOperationStatus.IS_FAILURE) {
            throw new RuntimeException("删除失败");
        }
        return Result.success();
    }

    @Override
    public Result getEntprTankById(Long id) {
        StorageTankSelectDTO storageTankSelectDTO = new StorageTankSelectDTO();
        // 查询储罐详情
        StorageTank entprTankById = storageTankMapper.getEntprTankById(id);
        BeanUtils.copyProperties(entprTankById, storageTankSelectDTO);
        // 查询储罐下的介质详情
        List<MajorHazardMaterial> majorMaterial = majorHazardMaterialMapper.getMajorMaterial(PartTypeEnum.PART_TYPE_ONE.getCode(), id);
        storageTankSelectDTO.setMajorHazardMaterials(majorMaterial);

        Long entprId = storageTankSelectDTO.getEntprId();
        EntprBasicInfo entprBasicInfo = entprBasicInfoMapper.getEntprBasicInfoById(entprId);
        String entprScope = entprBasicInfo.getEntprScope();
        if (StringUtils.isNotEmpty(entprScope)) {
            entprScope = "{\"data\":" + entprScope + "}";
            JSONObject jsonObject = JSON.parseObject(entprScope);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            List<EntprScopeDTO> entprScopeDTOS = jsonArray.toJavaList(EntprScopeDTO.class);
            storageTankSelectDTO.setEntprScope(entprScopeDTOS);
        }else{
            storageTankSelectDTO.setEntprScope(new ArrayList<>());
        }
        return Result.success(storageTankSelectDTO);
    }
}